cmake_minimum_required(VERSION 3.10)
project(lua VERSION 5.4.7 LANGUAGES C)

# 设置编译选项
set(CMAKE_C_STANDARD 99)

# if (MSVC)
#     set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /O2 /W3 /DLUA_COMPAT_5_3 /Zi")
#     set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF")
#     set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF")
# else()
#     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O2 -Wall -Wextra -DLUA_COMPAT_5_3")
# endif()


set(LUA_C src/lua.c)
set(LUAC_C src/luac.c)

# LUA LIB
add_definitions(-DLUA_BUILD_AS_DLL)
aux_source_directory("src" LIB_SRC)
list(REMOVE_ITEM LIB_SRC ${LUA_C})
list(REMOVE_ITEM LIB_SRC ${LUAC_C})
add_library("liblua" SHARED ${LIB_SRC}) # 源码编译生成动态库
add_library("liblua_static" STATIC ${LIB_SRC}) # 源码编译生成静态库

# LUA.EXE
add_executable("lua" ${LUA_C} ${LIB_SRC}) # 生成exe文件

# LUAC.EXE
add_executable("luac" ${LUAC_C} ${LIB_SRC}) # 生成可执行文件


# # 设置动态库的输出名称
# set_target_properties(liblua_shared PROPERTIES OUTPUT_NAME "lua")

# # 链接库
# if (MSVC)
#     target_link_libraries(lua liblua_shared)
#     target_link_libraries(luac liblua_shared)
# else()
#     target_link_libraries(lua liblua_shared m)
#     target_link_libraries(luac liblua_shared m)
# endif()

# 安装目标
install(TARGETS lua luac liblua liblua_static
    RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
    LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
    ARCHIVE DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
)

install(FILES src/lua.h src/luaconf.h src/lualib.h src/lauxlib.h src/lua.hpp
    DESTINATION ${CMAKE_INSTALL_PREFIX}/include
)

install(FILES doc/lua.1 doc/luac.1
    DESTINATION ${CMAKE_INSTALL_PREFIX}/man/man1
)

# 安装 PDB 文件
if (MSVC)
    install(FILES $<TARGET_PDB_FILE:lua> $<TARGET_PDB_FILE:luac> $<TARGET_PDB_FILE:liblua> $<TARGET_PDB_FILE:liblua_static>
        DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
        CONFIGURATIONS Release RelWithDebInfo Debug
    )
endif()

# 定义自定义命令
add_custom_target(test
    COMMAND lua -v
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)

add_custom_target(clean_all
    COMMAND ${CMAKE_COMMAND} -E remove -f lua luac liblua.a
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)

# 打印配置信息
add_custom_target(echo
    COMMAND ${CMAKE_COMMAND} -E echo "PLAT= ${PLAT}"
    COMMAND ${CMAKE_COMMAND} -E echo "CC= ${CMAKE_C_COMPILER}"
    COMMAND ${CMAKE_COMMAND} -E echo "CFLAGS= ${CMAKE_C_FLAGS}"
    COMMAND ${CMAKE_COMMAND} -E echo "LDFLAGS= ${CMAKE_EXE_LINKER_FLAGS}"
    COMMAND ${CMAKE_COMMAND} -E echo "LIBS= m"
    COMMAND ${CMAKE_COMMAND} -E echo "AR= ar"
    COMMAND ${CMAKE_COMMAND} -E echo "RANLIB= ranlib"
    COMMAND ${CMAKE_COMMAND} -E echo "RM= rm -f"
    COMMAND ${CMAKE_COMMAND} -E echo "UNAME= uname"
)